package com.bunnyhsu.controller;

import com.bunnyhsu.dto.Result;
import com.bunnyhsu.enums.FailEnum;
import com.bunnyhsu.service.AdminService;
import com.bunnyhsu.service.ImageService;
import com.bunnyhsu.service.TypeService;
import com.bunnyhsu.utils.ResultUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * Created by xl on 2018/4/14.
 */
@RestController
@CrossOrigin("*")
public class TypeController {
    @Autowired
    private TypeService typeService;
    @Autowired
    private AdminService adminService;

    @PostMapping("/getAllTypes")
    public Result getAllTypes(String token)
    {
        Result result = checkToken(token);
        if(result == null)
        {
            return ResultUtil.success(typeService.getAllTypes(),"");
        }
        else
        {
            return result;
        }
    }

    @PostMapping("/getTypeNameById")
    public Result getTypeNameById(int id, String token)
    {
        Result result = checkToken(token);
        if(result == null)
        {
            String typeName = typeService.getTypeById(id);
            if("".equals(typeName))
            {
                return ResultUtil.fail(FailEnum.TYPE_NONEXIST.getId(),FailEnum.TYPE_NONEXIST.getMsg());
            }
            else
            {
                return ResultUtil.success(typeService.getTypeById(id),"");
            }
        }
        else
        {
            return result;
        }

    }

    private Result checkToken(String token)
    {
        if(token == null)
        {
            return ResultUtil.fail(FailEnum.NO_ANTH.getId(), FailEnum.NO_ANTH.getMsg());
        }
        else if (adminService.comfirmToken(token))
        {
            return null;
        }
        else
        {
            return ResultUtil.fail(FailEnum.TOKEN_WRONG.getId(), FailEnum.TOKEN_WRONG.getMsg());
        }
    }
}
